package com.nf.mvc.argument;

import com.nf.mvc.MethodArgumentResolver;
import com.nf.mvc.support.WebTypeConverters;
import com.nf.mvc.util.ClassUtils;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Field;
import java.lang.reflect.Parameter;

public class PojoMethodArgumentResolver implements MethodArgumentResolver {
    @Override
    public boolean supports(Parameter parameter) {
        return ClassUtils.isPojo(parameter.getType());
    }

    @Override
    public Object resolveArgument(Parameter parameter, HttpServletRequest request) throws Exception {
        Class<?> type = parameter.getType();
        Object instance = type.newInstance();

        Field[] fields = type.getDeclaredFields();
        for (Field field : fields) {
            String name = field.getName();
            Object value = request.getParameter(name);

            value = WebTypeConverters.convert(value.toString(), field.getType());
            field.setAccessible(true);
            field.set(instance, value);
            field.setAccessible(false);
        }
        return instance;
    }
}
